<template>
  <div class="notice-container">

    <vab-query-form>
      <vab-query-form-left-panel :span="8">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
          添加
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="16">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <div>关键字：</div>
          </el-form-item>
          <el-form-item>

            <el-input
              v-model.trim="queryForm.keyword"
              placeholder="请输入搜索词"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleEdit">搜搜</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleEdit">发布</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>


    <el-table
      v-loading="listLoading"
      :data="list"
      @selection-change="setSelectRows"
    >
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="title"
        label="标题"
        width="300px"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="name"
        label="创建人"
        width="200px"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="section"
        label="部门"
        width="200px"
      />
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="create_time"
        label="创建时间"
        width="300px"
      />
      <el-table-column align="center" label="操作" >
        <template #default="{ row }">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(row)"
          >编辑
          </el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.page"
      :page-size="queryForm.list_row"
      :layout="layout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

  </div>
</template>

<script>
import {
  getList,
  doDelete,
  doFiled,
  getCheckTypes,
  saveChecks,
} from '@/api/activity'
import { upload } from '@/api/common'
import Edit from './components/ActivityEdit'

export default {
  name: 'Activity',
  components: { Edit },
  data() {
    return {
      list: [{
        title:'通知公告标题通知公告标题',
        name:'流星',
        section:'部门A',
        create_time:'2012-01-01 11:11',
      },{
        title:'通知公告标题通知公告标题',
        name:'流星',
        section:'部门A',
        create_time:'2012-01-01 11:11',
      },{
        title:'通知公告标题通知公告标题',
        name:'流星',
        section:'部门A',
        create_time:'2012-01-01 11:11',
      },{
        title:'通知公告标题通知公告标题',
        name:'流星',
        section:'部门A',
        create_time:'2012-01-01 11:11',
      },{
        title:'通知公告标题通知公告标题',
        name:'流星',
        section:'部门A',
        create_time:'2012-01-01 11:11',
      },{
        title:'通知公告标题通知公告标题',
        name:'流星',
        section:'部门A',
        create_time:'2012-01-01 11:11',
      },{
        title:'通知公告标题通知公告标题',
        name:'流星',
        section:'部门A',
        create_time:'2012-01-01 11:11',
      },{
        title:'通知公告标题通知公告标题',
        name:'流星',
        section:'部门A',
        create_time:'2012-01-01 11:11',
      }],
      listLoading: false,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: '',
      queryForm: {
        page: 1,
        list_row: 10,
        keyword: '',
        activity_range: null,
        activity_start: '',
        activity_end: '',
      },
      checksVisible: false,
      checkTypes: [],
      currentActivityId: null,
    }
  },
  watch: {
    'queryForm.activity_range'(range) {
      const [start, end] = range || ['', '']
      this.queryForm.activity_start = start
      this.queryForm.activity_end = end
    },
  },
  created() {
    this.fetchData()
  },
  methods: {
    setSelectRows(val) {
      this.selectRows = val
    },
    handleEdit(row) {
        console.log(row)
        const { id: manageAddEdit_id, manageAddEdit_name } = row
        this.$router.push({
          name: 'ManageAddEdit',
          query: { manageAddEdit_id, manageAddEdit_name },
        })
    },
    handleDelete(row) {
      if (row.id) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const msg = await doDelete({ activity_id: row.id })
          this.$baseMessage(msg, 'success')
          this.fetchData()
        })
      } else {
        if (this.selectRows.length > 0) {
          const ids = this.selectRows.map((item) => item.id).join()
          this.$baseConfirm('你确定要删除选中项吗', null, async () => {
            const { msg } = await doDelete({ ids })
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          this.$baseMessage('未选中任何行', 'error')
          return false
        }
      }
    },
    handleFiled(row) {
      const actionText = row.is_filed === '是' ? '解档' : '归档'
      const isFiledNew = row.is_filed === '是' ? '否' : '是'
      this.$baseConfirm(`你确定要${actionText}当前项吗`, null, async () => {
        const msg = await doFiled({
          activity_id: row.id,
          is_filed: isFiledNew,
        })
        this.$baseMessage(msg, 'success')
        this.fetchData()
      })
    },
    handleExpenses(row) {
      console.log(row)
      const { id: activity_id, activity_name } = row
      this.$router.push({
        name: 'ActivityExpenses',
        query: { activity_id, activity_name },
      })
    },
    handleSizeChange(val) {
      this.queryForm.list_row = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.queryForm.page = val
      this.fetchData()
    },
    queryData() {
      this.queryForm.page = 1
      this.fetchData()
    },
    async fetchData() {
      /*this.listLoading = true
      const { data, total } = await getList(this.queryForm)
      this.list = data
      this.total = total
      this.listLoading = false*/
    },
    showChecks(id) {
      this.currentActivityId = id
      /*getCheckTypes({ activity_id: id }).then((res) => {
        const types = res.map((type) => {
          return {
            ...type,
            fileList: type.check_img.map((img) => ({
              uid: Math.random(),
              url: img,
            })),
          }
        })
        // types.unshift({ id: 0, project_category: '未分配', fileList: [] })
        this.checkTypes = types
        this.checksVisible = true
      })*/
    },
    handleSaveChecks() {
      if (!this.validateChecks()) return
      const images = []
      const types = this.checkTypes
      types.forEach((type) => {
        const files = type.fileList
        const typeImages = files.map((file) => file.url).join()
        images.push({
          activity_expenses_id: type.id,
          check_img: typeImages,
        })
      })
      const imagesJson = JSON.stringify(images)
      saveChecks({
        activity_id: this.currentActivityId,
        check_img: imagesJson,
      }).then((res) => {
        this.checksVisible = false
        this.$baseMessage(res, 'success')
      })
    },
    onChecksExceed() {
      this.$baseMessage('最多只能上传 6 张图片哦', 'warning')
    },
    onChecksChange(fileList, index) {
      // 注: fileList 包含全部图片
      const type = this.checkTypes[index]
      // 处理待上传图片
      const formData = new FormData()
      fileList
        .filter((file) => file.raw)
        .forEach((file) => formData.append('file[]', file.raw))
      // 上传图片
      upload(formData).then((res) => {
        // 上传后处理
        const urls = res.url
        type.fileList = [
          ...fileList.filter((file) => !file.raw),
          ...urls.map((url) => ({ url })),
        ]
        this.$set(this.checkTypes, index, type)
      })
    },
    getUploadTypeLabel(type, index) {
      let label = type.project_category
      const num = type.fileList.length
      // label += ` ${index ? `(${num}/6)` : num}`
      label += ` (${num}/6)`
      return label
    },
    validateChecks() {
      const types = this.checkTypes
      for (const type of types) {
        const files = type.fileList
        for (const file of files) {
          if (file.url.startsWith('blob:')) {
            this.$baseMessage('图片上传中，请重试', 'error')
            return false
          }
        }
      }
      return true
    },
    removeCheck(typeIndex, fileIndex) {
      this.checkTypes[typeIndex].fileList.splice(fileIndex, 1)
      this.$forceUpdate()
    },
  },
}
</script>

<style lang="scss" scoped>
.search-input {
  width: 250px;
}

.checks-row {
  display: flex;
  align-items: center;
}

.check-item {
  position: relative;
  box-sizing: border-box;
  width: 100px;
  height: 100px;
  margin-right: 10px;
  background-position: center;
  background-size: cover;
  border: 1px solid #c0ccda;
  border-radius: 7px;
}

.check-mask {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: 0.3s;
}

.check-item:hover .check-mask {
  opacity: 1;
}

.check-delete {
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 20px;
  color: #fff;
  cursor: pointer;
  transform: translate(-50%, -50%);
}

::v-deep .el-upload--picture-card {
  position: relative;
  width: 100px;
  height: 100px;
}

.check-add {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
